package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.JTextPane;

import model.Carnet;
import model.Contact;
/**
 * this class is to set the action listener of the button searbygroup in the main window
 * @author Estelle
 *
 */

public class SearchByGroup implements ActionListener {
	private JTextField groupe;
	private Carnet carnet = new Carnet(" ");
	private JList<String> contacts;
	private JTextPane person = new JTextPane();
	
	public SearchByGroup(JTextField grp, JList<String> listperso, JTextPane text){
		FileDoc file = new FileDoc();
		carnet.copy(file.recupCarnet("Estelle"));
		groupe = grp;
		contacts = listperso;
		person = text;
	
	}
	
	 @Override
     public void actionPerformed(ActionEvent event) {
		 List<Contact> tmp = new ArrayList<Contact>();
		 String g = groupe.getText().toUpperCase();
		 
		 tmp = carnet.searchContactGroup(g);
		 
		 if(tmp.isEmpty()){
			 person.setText("Not a such group for " + g);
		 }
		 else {
			 person.setText("Result for " + g + "\n Choose your contact");
			 setlistContact(tmp);
		 }
		 
     }
	 

	public void setlistContact(List<Contact> list){
			int i =0;
			
			StringBuilder tmp = new StringBuilder();
			
			String[] contentlist = new String[list.size()];
			
			for(Contact con : list)
	        {
				tmp.append(con.getLastName()).append(" ").append(con.getFirstName());
				contentlist[i]=tmp.toString();
		        tmp.setLength(0);
		        i++;
	        }
			
			contacts.setListData(contentlist);
			
	}
}
